<template>
  <el-form
    size="large"
    :rules="FORM_RULES"
    ref="formRef"
    :model="formData"
    label-width="100px"
  >
    <el-form-item prop="title" label="tab名称">
      <el-input clearable placeholder="请输入tab名称" v-model="formData.title" />
    </el-form-item>
    <el-form-item prop="path" label="路径">
      <el-input clearable placeholder="请输入路由路径" v-model="formData.path" />
    </el-form-item>
    <el-form-item prop="fullPath" label="全路径">
      <el-input clearable placeholder="请输入路由全路径" v-model="formData.fullPath" />
    </el-form-item>
    <el-form-item prop="name" label="路由名称">
      <el-input clearable placeholder="请输入路由名称" v-model="formData.name" />
    </el-form-item>
    <el-form-item prop="component" label="组件地址">
      <el-input clearable placeholder="请输入组件地址，@/views/后面路径" v-model="formData.component" />
    </el-form-item>
    <el-form-item prop="redirect" label="重定向地址">
      <el-input clearable placeholder="请输入重定向地址" v-model="formData.redirect" />
    </el-form-item>
    <el-form-item prop="showOrder" label="代码排序">
      <el-input-number v-model="formData.showOrder" :step="2" :min="0"></el-input-number>
    </el-form-item>
    <el-form-item prop="remark" label="备注">
      <el-input :rows="3" clearable placeholder="请输入备注" v-model="formData.remark" type="textarea"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
      <el-button type="info" @click="handleClose">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { RuleBeanData, FORM_RULES } from '@/model/system/router/model'
import { saveForm, loadDataById } from '@/api/system/router/RouterManager'

const formRef = ref()
const props = defineProps({ fid: String, id: String, fPath: String })
const emit = defineEmits(['close-dialog', 'reload-data'])
const formData = ref({ ...RuleBeanData, fid: props.fid })

const handleClose = () => {
  emit('close-dialog')
}

const submitForm = async (formRef) => {
  if (!formRef) return
  formRef.validate(valid => {
    if (valid) {
      saveForm(formData.value).then(() => {
        ElMessage({
          message: '保存成功！',
          type: 'success',
          duration: 800
        })
        emit('reload-data')
        emit('close-dialog')
      }).catch(() => {
        ElMessage.error('保存失败！')
      })
    }
  })
}

onMounted(() => {
  if (props.id) {
    loadDataById(props.id).then(data => {
      formData.value = { ...data }
    })
  } else {
    formData.value.showOrder = 1
  }
})

watch(
  () => formData.value.path,
  () => {
    if (props.fPath) {
      formData.value.fullPath = props.fPath + '/' + formData.value.path
    } else {
      formData.value.fullPath = formData.value.path
    }
  }
)
</script>
